import type { RouteRecordRaw } from "vue-router";
/**
 * 根据试图自动注册路由
 * layouts文件夹用于存放父级路由
 * views文件夹用于放置子路由
 * 此接口功能为遍历layouts文件夹及views文件夹中的模板，自动生成路由，并自动为路由命名。
 * 父级路由命名规范为模板名称，子路由命名规范为父路由.子路由
 */

//vite官方提供的遍历文件系统的接口
const layouts = import.meta.glob('../../layouts/*.vue', { eager: true });
const views = import.meta.glob('../../views/**/*.vue', { eager: true });


function getRoutes(){
    const layoutRoutes = [] as RouteRecordRaw[]
    Object.entries(layouts).forEach(([file, module])=>{ 
        const route = getRouteByModule(file, module!)
        route.children = getChildrenRoutes(route)
        layoutRoutes.push(route)
    })
    return layoutRoutes
}

//获取layouts文件夹中的模板，生成路由,并将子路由命名改为路由.链接 例如：admin.user
function getRouteByModule(file:string,module:{[key:string]:any}){
   const name = file.replace(/.+layouts\/|.+views\/|\.vue/gi,'');
   const route = {
        name:name.replace('/','.'),
        path:`/${name}`,
        component:module.default,
   } as RouteRecordRaw
    //如果模块中自定义了路由，就采用模块中的自定义路由
   return Object.assign(route,module.default?.route)
}
//获取子路由
function getChildrenRoutes(layoutRoute:RouteRecordRaw){
    const routes = [] as RouteRecordRaw[]
    Object.entries(views).forEach(([file,module])=>{
        if(file.includes(`../../views/${layoutRoute.name as unknown as string}`)){
            const route  = getRouteByModule(file,module!)
            routes.push(route)
        }   
    }) 
    return routes
}

export default getRoutes